﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace MvcClient.Pages.Account
{
    public class LogoutModel : PageModel
    {
        //public void OnGet()
        //{

        //}
        private readonly ILogger<LogoutModel> _logger;
        /// <summary>
        /// The schemes
        /// </summary>
        protected readonly IAuthenticationSchemeProvider Schemes;

        /// <summary>
        /// The handlers
        /// </summary>
        protected readonly IAuthenticationHandlerProvider Handlers;
        private readonly IOptions<AuthenticationOptions> _authOptions;

        public string EndSessionUrl { get; set; }

        public LogoutModel(
            IAuthenticationSchemeProvider schemes,
            IAuthenticationHandlerProvider handlers,
            IOptions<AuthenticationOptions> options,
            ILogger<LogoutModel> logger)
        {

            _logger = logger;

            _authOptions = options;
            Schemes = schemes;
            Handlers = handlers;
        }


        public async Task<IActionResult> OnGetAsync()
        {
            string idToken = await HttpContext.GetTokenAsync("id_token");
            string loginProvider = HttpContext.User.Identity.AuthenticationType;
            // ===================================
            var opt = _authOptions;
            var defaultScheme = await Schemes.GetDefaultAuthenticateSchemeAsync();
            var s2 = await Schemes.GetDefaultChallengeSchemeAsync();
            var s3 = await Schemes.GetDefaultSignInSchemeAsync();
            var handler = await Handlers.GetHandlerAsync(HttpContext, defaultScheme.Name);
            var result2 = await handler.AuthenticateAsync();
            // ===================================

            await HttpContext.SignOutAsync("Cookies");
            await HttpContext.SignOutAsync("oidc");

            //HttpContext.Session.Clear();

            if (!string.IsNullOrEmpty(idToken) && !string.IsNullOrEmpty(loginProvider))
            {
                // we have an external OIDC provider here.
                var clientSignoutCallback = $"{Request.Scheme}://{Request.Host}/Identity/Account/SignoutCallbackOidc";
                
                var endSession = "https://localhost:5000/connect/endsession";
                EndSessionUrl = $"{endSession}?id_token_hint={idToken}&post_logout_redirect_uri={clientSignoutCallback}";
                // this redirect is to the provider to log everyone else out.  
                // We will get a double hit here, as our $"{Request.Scheme}://{Request.Host}/Account/SignoutFrontChannel";
                // will get hit as well.  
                return new RedirectResult(EndSessionUrl);
            }

            return RedirectToPage("/Index");
        }
    }
}